<template>
	<div style="height: 100%">
		<cl-crud ref="crud" @load="onLoad">
			<cl-pagefull>
				<template #head>
					<el-row type="flex">
						<cl-filter-group v-model="search" @reset="changeBiz">
							<cl-filter label="事业部">
								<cl-select
									v-model="search.biz_id"
									placeholder="请选择"
									filterable
									@change="changeBiz"
									style="width: 160px"
								>
									<el-option
										v-for="item in business"
										:key="item.biz_id"
										:label="item.biz_name"
										:value="item.biz_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="分公司">
								<cl-select
									v-model="search.company_id"
									placeholder="请选择"
									filterable
									style="width: 160px"
									@change="refresh"
									clearable
								>
									<el-option label="全部" value="" />

									<el-option
										v-for="item in bizRefData.company"
										:key="item.company_id"
										:label="item.company_name"
										:value="item.company_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="品牌">
								<cl-select
									v-model="search.bra_id"
									placeholder="全部"
									filterable
									style="width: 160px"
									clearable
									@change="refresh"
									multiple
									collapse-tags
								>
									<el-option
										v-for="item in bizRefData.brand"
										:key="item.bra_id"
										:label="item.bra_name"
										:value="item.bra_id"
									/>
								</cl-select>
							</cl-filter>
							<cl-filter label="所属部门">
								<!-- <cl-select
								v-model="search.dept_id"
								placeholder="请选择"
								filterable
								clearable
							>
								<el-option label="全部" value="" />
								<el-option
									v-for="item in deptList"
									:key="item.dept_id"
									:label="item.dept_name"
									:value="item.dept_id"
								/>
							</cl-select> -->
								<cl-cascader
									clearable
									v-model="search.dept_ids"
									:options="deptList"
									collapse-tags
									style="min-width: 230px"
									:props="{
										multiple: true,
										value: 'dept_id',
										label: 'dept_name'
									}"
									filterable
									@change="refresh"
								/>
							</cl-filter>

							<!-- <cl-filter label="收款类型">
								<cl-select
									v-model="search.post"
									placeholder="请选择"
									filterable
									style="width: 160px"
									clearable
									@change="refresh"
								>
									<el-option label="全部" value="" />
									<el-option
										v-for="item in searchReportStatusOpt"
										:key="item.value"
										:label="item.label"
										:value="item.value"
									/>
								</cl-select>
							</cl-filter> -->
							<cl-filter label="收款时间">
								<cl-date-picker
									v-model="search.date"
									type="daterange"
									range-separator="至"
									start-placeholder="开始日期"
									end-placeholder="结束日期"
									value-format="yyyy-MM-dd"
									style="width: 230px"
									:clearable="false"
									@change="refresh"
								/>
							</cl-filter>
						</cl-filter-group>
						<cl-flex1 />
						<cl-table-handle
							:print="printParams"
							:columns="initColumns"
							v-model="table.columns"
							@export-file="exportFile"
						/>
					</el-row>
				</template>
				<el-row>
					<!-- 数据表格 -->
					<cl-table v-bind="table" id="collectReport" ref="table" show-summary>
						<cl-empty slot="empty" />
					</cl-table>
				</el-row>
			</cl-pagefull>
		</cl-crud>
	</div>
</template>

<script>
	import dayjs from "dayjs";
	import { exportExcel } from "@/utils/excel";
	import { cloneDeep } from "cl-admin/utils";
	import { delEmptyChildren } from "@/utils";
	export default {
		data() {
			return {
				printParams: {
					id: "collectReport",
					popTitle: "收款报表"
				},
				// 表格配置
				table: {
					"context-menu": ["refresh"],
					sortRefresh: false,
					columns: [],
					props: {
						showSummary: true,
						summaryMethod: this.getSummaries
					}
				},
				initColumns: [
					{
						label: "事业部",
						prop: "biz_name",
						minWidth: 150,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "部门",
						prop: "dept_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "分公司",
						prop: "company_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "品牌",
						prop: "bra_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "所属组员",
						prop: "user_name",
						minWidth: 120,
						align: "left",
						showOverflowTooltip: true
					},
					{
						label: "定金总额（￥）",
						prop: "total_amount",
						width: 120
					},
					{
						label: "定金总数",
						prop: "total_num",
						width: 120
					},
					{
						label: "定金金额（￥）",
						prop: "all_amount",
						width: 120
					},
					{
						label: "优惠金额（￥）",
						prop: "all_discount",
						width: 120
					},
					{
						label: "实付金额（￥）",
						prop: "real_pay",
						width: 120
					},
					{
						label: "定金数",
						prop: "count",
						width: 120,
						sortable: true,
						formatter: (row) => row.count || 0
					},
					{
						label: "临时码总金额（￥）",
						prop: "diff_amount",
						width: 150
					},
					{
						label: "临时码定金数",
						prop: "diff_num",
						width: 150
					},
				],
				deptList: [], //部门数据
				//收款报表 搜索表单
				searchReportStatusOpt: [
					{ value: 1, label: "售前" },
					{ value: 2, label: "售中" },
					{ value: 5, label: "门店" }
				],
				search: {
					date: [
						dayjs()
							// .startOf("month")
							.format("YYYY-MM-DD"),
						dayjs().format("YYYY-MM-DD")
					],
					biz_id: "",
					company_id: "",
					bra_id: [],
					post: "",
					dept_ids: [] // 部门
				}
			};
		},
		computed: {
			bizRefData() {
				const { biz_id } = this.search;
				return this.getBizRefData(biz_id);
			}
		},
		created() {
			this.search.biz_id = this.getCurrBiz();
			this.init();
			this.table.columns = cloneDeep(this.initColumns);
		},
		methods: {
			async init() {
				const { biz_id } = this.search;
				this.getBizRefBrand(biz_id);
				this.getBizRefCompany(biz_id);
				// this.search.bra_id = this.brandList[0]?.value;
				this.initData();
			},
			async initData() {
				const { biz_id } = this.search;

				// this.search.bra_id = this.brandList[0]?.value;
				this.deptList = delEmptyChildren(
					(await this.$store.dispatch("common/getDept", {
						biz_id,
						needCascader: true
					})) || []
				);
			},
			onLoad({ ctx, app }) {
				ctx.service(this.$service.finance)
					.set("dict", {
						// 请求
						api: {
							page: "orderStatement"
						}
					})
					.done();
				// app.refresh(this.search);
			},
			// crud刷新
			refresh() {
				this.$refs.crud.refresh({ page: 1, ...this.search });
				this.$nextTick(() => {
					this.$refs.table?.calcMaxHeight?.();
				});
			},
			async changeBiz(v) {
				this.search = {
					...this.search,
					company_id: "",
					bra_id: [],
					dept_id: "",
					dept_ids: []
				};
				this.init();
				this.refresh();
			},
			// 表格合计
			getSummaries({ columns, data }) {
				let sumKeys = ["all_amount", "count", "all_discount", "real_pay", "total_amount", "total_num", "diff_amount", "diff_num"];
				return columns.map((column, index) => {
					if (index === 0) {
						return "合计";
					}
					if (!sumKeys.includes(column.property)) return "";
					const values = data.map((item) => Number(item[column.property]));
					let sum = values.reduce((prev, curr) => {
						const value = Number(curr);
						if (!isNaN(value)) {
							return prev + curr;
						}
						return prev;
					}, 0);
					return this.toFixed(sum);
				});
			},
			// 导出EXCEl
			exportFile() {
				exportExcel("#collectReport");
			}
		}
	};
</script>
